import { useState } from 'react';

import { useRequest } from 'ahooks';
import { Col, Empty, Input, Row, Skeleton } from 'antd';

import { store } from '@/store';

import {
  sysApplicationGetIdSecret,
  sysApplicationMyApplication
} from '@/services/base/quanxianmokuaiyingyongbiaojiekou';
import { parseSrc } from '@/utils';

import styles from './index.module.scss';

export type BizObject = BASE.SysApplication;

const Page: React.FC = () => {
  // 搜索
  const [searchValue, setSearchValue] = useState<string>('');
  const list = useRequest(async () => {
    return (await sysApplicationMyApplication({})).data;
  });

  const onCardClick = async (item: BizObject) => {
    try {
      const code = await sysApplicationGetIdSecret(
        {
          id: item.id.toString()
        },
        {
          tupleResponse: false
        }
      );

      if (!code.data?.appId) {
        store.app?.message.error('获取应用ID和密钥失败');
      }

      window.open(
        `${import.meta.env.VITE_PROXY_KEY}app/oauth/authorize?appId=${
          code.data!.appId
        }&redirectUri=${item.redirectUrl}`,
        '_blank'
      );
    } catch (error) {
      // @ts-ignore
      console.log('RES', error);
    }
  };

  return (
    <>
      <div className={styles['search']}>
        <Input.Search
          placeholder="输入应用名称搜索"
          size="large"
          allowClear
          value={searchValue}
          onChange={(e) => {
            setSearchValue(e.target.value);
          }}
          style={{
            width: 280
          }}
        />
      </div>

      <Skeleton
        active
        loading={list.loading}
        paragraph={{
          rows: 4
        }}
      />

      {(list.data || []).length <= 0 ? (
        <Empty />
      ) : (
        <div className={styles['list']}>
          <Row gutter={[16, 16]}>
            {(list.data || []).map((item) => {
              return (
                <Col xs={24} sm={12} md={8} lg={6} xl={4} xxl={4} key={item.id}>
                  <div className={styles['card']} onClick={onCardClick.bind(null, item)}>
                    <div className={styles['card-icon']}>
                      <img src={parseSrc(item.appIcon)} alt={item.appName} />
                    </div>
                    <div className={styles['card-title']} title={item.appName}>
                      <div className={styles['title']}>{item.appName}</div>
                    </div>
                  </div>
                </Col>
              );
            })}
          </Row>
        </div>
      )}
    </>
  );
};

export default Page;
